package cycling.taxi.com.ui.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cycling.taxi.com.R;
import cycling.taxi.com.entity.BusinessCheckpoint;
import cycling.taxi.com.eventbus.SetTime;
import cycling.taxi.com.ui.fragment.FixFrgt;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.ToastUtil;

public class FixlocationlistsActivity extends Activity implements View.OnClickListener{

    @InjectView(R.id.bmapView)
    MapView mMapView = null;
    @InjectView(R.id.back)
    ImageView back;
    @InjectView(R.id.title_text)
    TextView title_text;
    @InjectView(R.id.checkpoint_name)
    TextView checkpoint_name;
    @InjectView(R.id.distance_f)
    TextView distance;
    @InjectView(R.id.address_fix)
    TextView address;
    @InjectView(R.id.loc)
    ImageView loc;
    private BaiduMap mBaiduMap;
    BusinessCheckpoint checkpoint;
    LatLng ptStart=null;
    LatLng edpoint=null;
    private PopupWindow mPopupWindow;
    private LocationClient mLocationClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fixlocation);
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        SDKInitializer.initialize(this);
        initTopUI();
        initUI();
        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//扫描时间
        MyLocationListener myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener);// //注册监听函数
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        back.setOnClickListener(this);
        loc.setOnClickListener(this);
    }
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            //经纬度
            if(ptStart==null){
                double lati = location.getLatitude();
                double longa = location.getLongitude();
                //打印出当前位置
                ptStart=new LatLng(lati,longa);
                ToastUtil.getInstance().toast("null");
            }

        }
    }
    public void initUI(){
        mBaiduMap = mMapView.getMap();
        //地图上比例尺
        mMapView.showScaleControl(false);
        // 隐藏缩放控件
        mMapView.showZoomControls(false);
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //定义Maker坐标点
        checkpoint= (BusinessCheckpoint) getIntent().getSerializableExtra("Item");
        ptStart=getIntent().getParcelableExtra("ptStart");
        edpoint=getIntent().getParcelableExtra("LatLng");
        checkpoint_name.setText(checkpoint.getName());
        distance.setText(String.valueOf(Double.parseDouble(checkpoint.getDistance())/10));
        address.setText(checkpoint.getAddress());
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_stop_red);
        OverlayOptions option = new MarkerOptions().position(edpoint).icon(bitmap);//构建MarkerOption，用于在地图上添加Marker
        mBaiduMap.addOverlay(option);//在地图上添加Marker，并显示
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(edpoint).zoom(15).build()));
        InitpopupView();

    }
    public void initTopUI(){
        title_text.setText("检修点位置");
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.back){
            finish();
        }
        if(v.getId()==R.id.loc){
            //  startRoutePlanDriving_fixfrgt();
//            Intent intent = new Intent(this.getActivity(), FindMap.class);
//            startActivity(intent);
    //        LogUtil.e(ptStart.toString());
            mPopupWindow.showAsDropDown(v);
        }
    }
    public void InitpopupView(){
        mPopupWindow=new MapPopWindow(this,ptStart,edpoint);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
    }
    @Subscribe
    public void onEvent(SetTime time){
        LogUtil.d("========"+time.getTime().getLastTime());
        Double Long= Double.parseDouble(time.getTime().getLongitude());
        Double Lan=Double.parseDouble(time.getTime().getLatitude());
        ptStart=new LatLng(Lan,Long);
        // website_tv.setText(ptStart.toString());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
        mLocationClient.stop();
    }
    public void startRoutePlanDriving_fixfrgt() {

        // LatLng ptEnd = new LatLng(25.28693,110.322239);

        // 构建 route搜索参数
        RouteParaOption para = new RouteParaOption()
                .startPoint(ptStart)
                .endPoint(edpoint);
        try {
            BaiduMapRoutePlan.openBaiduMapDrivingRoute(para,FixlocationlistsActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
            showDialog();
        }

    }
    /**
     * 提示未安装百度地图app或app版本过低
     */
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                OpenClientUtil.getLatestBaiduMapApp(FixlocationlistsActivity.this);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();

    }
    public class MapPopWindow extends PopupWindow {

        private View mMenuView;
        private TextView baidumap, clear;

        public MapPopWindow(final Activity context, final LatLng start, final LatLng end) {
            super(context);
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mMenuView = inflater.inflate(R.layout.layout_popupwindow, null);
            baidumap = (TextView) mMenuView.findViewById(R.id.baidumap);
            clear = (TextView) mMenuView.findViewById(R.id.clear);
            //取消按钮
            clear.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    //销毁弹出框
                    dismiss();
                }
            });
            //设置按钮监听
            baidumap.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startRoutePlanDriving_fixfrgt();
                    //   BaiduMapRoutePlan.openBaiduMapDrivingRoute(para,context);
                }
            });
            //设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            //设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ActionBar.LayoutParams.WRAP_CONTENT);
            //设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ActionBar.LayoutParams.WRAP_CONTENT);
            //设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);

        }
    }}
